import {
  getAddressList,
  updateAddress,
  getChinaList
} from '../../api/customerApi.js'

import router from '../../router/index.js'


export default {
  namespaced: true,
  state: {
    //默认地址
    address: {},
    //地址列表
    address_list: [],
    //所有地区列表
    china_list: []
  },
  getters: {},
  mutations: {
    //设置默认地址
    set_address(state, value) {
      state.address_list.forEach(addr => {
        if (addr.uaddr_isdefault == 1) {
          state.address = addr
        }
      })
    },
    //地址列表
    set_address_list(state, value) {
      state.address_list = value
    },
    //设置区域列表
    set_china_list(state, value) {
      state.china_list = value
    }
  },
  actions: {
    get_china_list(context) {
      getChinaList({
        pid: 0
      }).then(response => {
        context.commit('set_china_list', response.data.data)
      })
    },
    //获取当前用户所有收货地址列表
    get_address_list(context) {
      getAddressList({}).then(response => {
        if (response.data.httpcode == 200) {
          context.commit('set_address_list', response.data.data)
          context.commit('set_address', response.data.data)
        }
      })
    },
    update_address(context, value) {
      //把之前默认地址修改成非默认
      context.state.address_list.forEach(addr => {
        if (addr.uaddr_id != value.uaddr_id && addr.uaddr_isdefault == 1) {
          addr.uaddr_isdefault = 0
          updateAddress(addr).then(response => {})
        }
      })
      //设置默认地址
      updateAddress(value).then(response => {
        if (response.data.httpcode == 200) {
          context.dispatch('get_address_list')
        }
      })
    }
  }
}
